package com.lht.femalecat.netty.resolve;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.util.Date;

/**
 * @Author:骆宏图
 * @CreateDate: 8:57 2018/7/29.
 * @Description:
 * @Modified By:
 */
public class TimeServer {

    public static void main(String[] args){
        EventLoopGroup  accept=new NioEventLoopGroup();
        EventLoopGroup proccess=new NioEventLoopGroup();

        ServerBootstrap b=new ServerBootstrap();

        try {

            b.group(accept,proccess).channel(NioServerSocketChannel.class);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(new ServerHandler());
                }
            });

            ChannelFuture f  = b.bind("127.0.0.1",8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            accept.shutdownGracefully();
            proccess.shutdownGracefully();
        }
    }

    private static class ServerHandler extends ChannelInboundHandlerAdapter{

        private  static  int counter;

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body=(String)msg;
            System.out.println("The Time body :"+ body+"次数："+ ++counter);

            String currentTime="Query Time Order".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"Bad Order";
            currentTime+=System.getProperty("line.separator");
            ByteBuf res= Unpooled.copiedBuffer(currentTime.getBytes());
            ctx.writeAndFlush(res);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }
    }
}
